import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
import qs from 'qs'
let isRepeatRefresh = false
const requests: any[] = []
const request = axios.create({

})
function redirectLogin () {
  router.push({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}
function refreshToken () {
  return axios.create()({
    method: 'POST',
    url: '/front/user/refresh_token',
    data: qs.stringify({
      refreshtoken: store.state.user.refresh_token
    })
  })
}
request.interceptors.request.use(config => {
  const { user } = store.state
  if (user && user.access_token) {
    config.headers.Authorization = user.access_token
  }
  return config
}, error => {
  return Promise.reject(error)
})
request.interceptors.response.use(response => {
  return response
}, async error => {
  if (error.response) {
    const { status } = error.response
    if (status === 400) {
      Message.error('请求参数错误')
    } else if (status === 401) {
      Message.error('登录超时')
      if (!store.state.user) {
        redirectLogin()
        return Promise.reject(error)
      }
      if (!isRepeatRefresh) {
        isRepeatRefresh = true
        return refreshToken().then(res => {
          if (!res.data.success) {
            throw new Error('刷新token失败')
          }
          store.commit('setUser', res.data.content)
          requests.forEach(cb => cb())
          return request(error.config)
        }).catch(err => {
          redirectLogin()
          store.commit('setUser', null)
          return Promise.reject(err)
        }).finally(() => {
          isRepeatRefresh = false
        })
        return new Promise(resolve => {
          requests.push(() => {
            resolve(request(error.config))
          })
        })
      }
    } else if (status === 403) {
      Message.error('没有权限，请联系管理员')
    } else if (status === 404) {
      Message.error('请求资源不存在')
    } else if (status >= 500) {
      Message.error('服务端错误，请联系管理员')
    }
  } else if (error.request) { // 请求发出去没有收到响应
    Message.error('请求超时，请刷新重试')
  } else { // 在设置请求时发生了一些事情，触发了一个错误
    Message.error(`请求失败：${error.message}`)
  }
  return Promise.reject(error)
})

export default request
